package findTheDistanceValue;

import java.util.Arrays;

public class Solution {
    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        // 思路 排序 + 二分
        // 在arr2中找有没有属于x-d到x+d的数字
        Arrays.sort(arr2);
        int m = arr2.length;
        int ans = 0;
        for (int x: arr1) {
            int l =0;
            int r = m-1;
            boolean canAdd =true;
            while (l<=r){
                int mid = (l+r)/2;
                if(arr2[mid]>=x+d){
                    r = mid-1;
                }else if(arr2[mid]<=x-d){
                    l = mid+1;
                }else {
                    canAdd=false;
                    break;
                }
            }
            if(canAdd){
                ans++;
            }
        }
        return ans;
    }
}
